<template>
  <el-upload
    class="upload-demo"
    :action="action"
    name="img"
    :limit="lim"
    style="width:30%"
    :on-exceed="handleExceed"
    :on-success="handleSuccess"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :file-list="fileList"
    list-type="picture"
  >
    <el-button size="small" type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">
      只能上传jpg/png文件，且不超过500kb
    </div>
  </el-upload>
</template>

<script>
import config from "@/utils/config.js";
export default {
  name: "",
  props: {
    url: String, //回显 //多个地址用","分隔
    limit: Number, //最多传几张图片
    cb: Function, //获取图片的钩子
  },
  data() {
    return {
      fileList: [],
      lim: 1,
      action: config.baseURL + "api/savePic", //图片上传接口
    };
  },
  components: {
      config
  },
  methods: {
    handleRemove(file, fileList) {
      let res = [];
      var _this = this;
      fileList.map((e, i) => {
        res.push({
          //向父组件传这样的数据格式
          status: e.status,
          name: e.name,
          size: e.size,
          uid: e.uid,
          file: e.raw,
          url:
            e.response && e.response.data
              ? config.baseURL + e.response.data
              : _this.fileList[i].url, // e.response.data上传图片， _this.fileList[i].url：回显图片
          code: e.code,
        });
      });
      this.$emit("cb", res);
    },
    handlePreview(file) {},
    handleSuccess(response, file, fileList) {
      let res = [];
      var _this = this;
      fileList.map((e, i) => {
        res.push({
          //向父组件传这样的数据格式
          status: e.status,
          name: e.name,
          size: e.size,
          uid: e.uid,
          file: e.raw,
          url:
            e.response && e.response.data
              ? config.baseURL + e.response.data
              : _this.fileList[i].url,
          code: e.code,
        });
      });
      this.$emit("cb", res);
    },
    handleExceed(files, fileList) {},
  },
  watch: {
    url: {
      handler(val) {
        if (!val || !val.length) {
          return;
        }
        if (!Array.isArray(val)) {
          val = val.replace(/\"/g, ""); //解决后端图片地址不规范："["url"]" ""url""
          val = val.replace(/\[/g, "");
          val = val.replace(/\]/g, "");
          val = val.replace(/\\/g, "");
          val = val.split(",");
        }

        val = val.map((e) => {
          //解决相对图片路径问题
          if (/http/.test(e)) return e;
          return (e = config.baseURL + e);
        });
        this.fileList = val.map((e) => ({
          //显示name和图片
          name: e,
          url: e,
        }));
      },
      immediate: true,
    },
    limit: {
      handler(val) {
        if (!val && val < 1) {
          return;
        }
        this.lim = parseInt(val);
      },
      immediate: true,
    },
  },
  computed: {},
  created() {},
  mounted() {},
};
</script>

<style lang="less" scoped>
</style>
